package com.balloon.springboot.generate.config;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
public class FreeMarkerInit {

//    @Autowired
//    private ResourceLoader resourceLoader;

    private static final FreeMarkerInit single = new FreeMarkerInit();

    public FreeMarkerInit() {}

    //静态工厂方法
    public static FreeMarkerInit getInstance() {
        return single;
    }

    public Template getDefinedTemplate(String templatePath, String templateName) throws IOException {
        //配置类
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
//        Resource resource = resourceLoader.getResource(templatePath);
//        ClassPathResource resource = new ClassPathResource(templatePath);
//        System.out.println(resource.getURL());
        File file = new File(templatePath);
//        cfg.setDirectoryForTemplateLoading(resource.getFile());
        cfg.setDirectoryForTemplateLoading(file);
       // cfg.setDirectoryForTemplateLoading(new File("D:/springboot/fast-code/src/main/resources/templates/"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        return cfg.getTemplate(templateName);
    }
}
